<template>
  <div id="about" class="flex-x-y-center">
    <div class="admin">
      <div class="main" v-if="show">
        <div v-if="fabuVisiable" class="row flex-x-y-center">
          <!-- <span>欢迎您{{ currentUser.username }}</span> -->
          <span style="margin: 0 10px">最新发布人：{{ fabuObj.faburen }}</span>
          <span>最新发布时间：{{ fabuObj.tjTime }}</span>
          <span @click="moreDo" class="moreDo">{{
            moreVisiable ? "收起" : "展开"
          }}</span>
        </div>
        <div v-else class="row flex-x-y-center">
          今日还未发布<span @click="moreDo" class="moreDo">{{
            moreVisiable ? "收起" : "展开"
          }}</span>
        </div>

        <div>
          <div class="row" v-if="moreVisiable">
            <div class="left">菜品：</div>
            <div class="middle">
              <el-input v-model="foodName" placeholder="请输入菜品"></el-input>
            </div>
            <div class="right" style="text-align: right">
              <el-button @click="delFood" type="danger">删除菜品</el-button>
              <el-button @click="addFood" type="primary">新增菜品</el-button>
            </div>
          </div>
          <div class="row" v-if="moreVisiable">
            <div class="left">用户：</div>
            <div class="middle yonghu">
              <el-select
                v-model="diancanren"
                filterable
                placeholder="请选择用户"
              >
                <el-option
                  v-for="item in yonghuArr"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
            <div class="right" style="text-align: right">
              <el-button
                class="marginL10"
                style="text-align: right"
                @click="delDiancan"
                type="danger"
                >删除点餐</el-button
              >
              <el-button @click="addUser" type="primary">添加用户</el-button>
            </div>
          </div>
          <div class="row">
            <div class="left">当前菜品：</div>
            <div class="middle">
              <div>
                <el-checkbox @change="handleCheckAllChange">全选</el-checkbox>
                <el-checkbox-group v-model="caipinSelectArr">
                  <el-checkbox
                    v-for="info in caipinArr"
                    :label="info.caipin"
                    :key="info.id"
                  >
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="left">点餐时间：</div>
            <div class="middle">
              <el-time-picker
                v-model="startTime"
                placeholder="开始时间点"
                value-format="yyyy-MM-dd HH:mm:ss"
                @blur="compareTime"
              >
              </el-time-picker>
            </div>
            <div class="right">
              <el-time-picker
                v-model="endTime"
                placeholder="截止时间点"
                value-format="yyyy-MM-dd HH:mm:ss"
                @blur="compareTime"
              >
              </el-time-picker>
            </div>
          </div>
          <!-- <div class="row">
            <div class="left">发布人：</div>
            <div class="middle">
              <el-select v-model="faburen" filterable placeholder="请选择">
                <el-option
                  v-if="item.fabu == '是'"
                  v-for="item in yonghuArr"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <el-button
                class="marginL10"
                v-if="fabuVisiable"
                @click="delFabu"
                type="danger"
                >删除今日发布</el-button
              >
            </div>
          </div> -->
          <div class="row">
            <div class="left">备注：</div>
            <div class="middle">
              <el-input
                placeholder="请输入备注"
                type="textarea"
                :rows="3"
                v-model="remark"
              ></el-input>
            </div>
          </div>
          <div class="row flex-x-y-center relative">
            <el-button
              class="marginL10"
              v-if="fabuVisiable"
              @click="delFabu"
              type="danger"
              >删除今日发布</el-button
            >
            <el-button type="primary" style="width: 120px" @click="fabu"
              >发布</el-button
            >
            <!-- <el-button type="primary" style="width: 120px" @click="fabuAgain"
              >二次发布</el-button
            > -->
            <!-- <span class="goto" @click="diancan">去点餐</span> -->
            <!-- <el-button @click="diancan" style="width: 120px">去点餐</el-button> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  addUser,
  getYonghu,
  getFabu,
  getFoods,
  addFood,
  delFood,
  delDiancan,
  delFabu,
  fabu,
} from "@/api/api";
export default {
  data: function () {
    return {
      moreVisiable: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      foodName: "",
      caipinSelectArr: [],
      caipinArr: [],
      startTime: "",
      endTime: "",
      faburen: "",
      remark: "",
      fabuVisiable: false,
      woyaofabu: true,
      fabuObj: {},
      yonghuArr: [],
      show: false,
      diancanren: "",
      currentUser: {},
      orderObj:{},
    };
  },
  created() {
    let orderArr = this.$store.state.food.caipinOrder;
    let arr = [];
    orderArr.forEach((item, index) => {
      this.orderObj[item] = index + 1;
    });
    this.currentUser = this.$store.state.food.userObj;
    this.faburen = this.currentUser.id;
    let nowTime = new Date();
    let year = nowTime.getFullYear();
    let month = nowTime.getMonth() + 1;
    let day = nowTime.getDate();
    this.startTime = new Date(year, month, day, 18, "00");
    this.endTime = new Date(year, month, day, 18, "30");
    this.getFoods();
    this.getYonghu();
  },
  methods: {
    moreDo() {
      this.moreVisiable = !this.moreVisiable;
    },
    compareTime() {
      let st = this.startTime.toString().includes("时间")
        ? this.startTime.FormatCopy("yyyy-MM-dd hh:mm:ss")
        : this.startTime;
      let et = this.endTime.toString().includes("时间")
        ? this.endTime.FormatCopy("yyyy-MM-dd hh:mm:ss")
        : this.endTime;
      let startTime = st;
      let endTime = et;
      console.log("startTime", startTime);
      console.log("endTime", endTime);
      if (startTime && endTime) {
        endTime = new Date(endTime.allReplace("-", "/"));
        startTime = new Date(startTime.allReplace("-", "/"));
        if (startTime >= endTime) {
          // alert("错误")
          // this.endTime = startTime;
        } else {
          // alert("正确")
        }
      }
    },
    addUser() {
      //prompt层
      this.$prompt("输入用户名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          if (value == "") {
            this.$message("用户名不能为空");
            return;
          }
          if (this.getUsernameStatus(value)) {
            this.$message("用户已经存在");
            return;
          }
          addUser({ username: value }).then((res) => {
            if (res.affectedRows == 1) {
              this.getYonghu();
              this.$message({
                type: "success",
                message: "成功添加",
              });
            } else {
              this.$message({
                type: "error",
                message: "添加失败",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    getUsernameStatus(name) {
      let arr = this.yonghuArr.filter((item) => {
        return item.username == name;
      });
      return arr[length] ? true : false;
    },
    getUsername(id) {
      return this.yonghuArr.filter((item) => {
        return item.id == id;
      })[0].username;
    },
    delDiancan() {
      if (this.diancanren == "") {
        this.$message("点餐人不能为空");
        return;
      }
      let username = this.getUsername(this.diancanren);
      delDiancan({
        diancanren: username,
        nowDay: new Date().Format("yyyy-MM-dd"),
      }).then((res) => {
        if (res.affectedRows == 1) {
          this.$message({
            message:`成功删除${username}今日点餐信息`,
            type:"success"
          });
        } else {
          this.$message({
            message:`没有${username}今日点餐信息`,
            type:"error"
          });
        }
      });
    },
    handleCheckAllChange(val) {
      this.caipinSelectArr = [];
      if (val) {
        this.caipinArr.forEach((item, index) => {
          this.caipinSelectArr.push(item.caipin);
        });
      }
    },
    diancan() {
      // location.href = encodeURI("etekcity.html");
      this.$router.push("etekcity");
    },
    getYonghu() {
      getYonghu().then((res) => {
        this.yonghuArr = res;
      });
    },
    getFabu() {
      getFabu({
        nowDay: new Date().Format("yyyy-MM-dd"),
      }).then((res) => {
        if (res.length) {
          this.fabuVisiable = true;
          this.woyaofabu = false;
          this.fabuObj = res[res.length - 1];

          this.startTime = this.fabuObj.startTime;
          this.endTime = this.fabuObj.endTime;
          this.caipinSelectArr = this.fabuObj.caipin.split(",");
          this.remark = this.fabuObj.remark;
        }
        setTimeout(() => {
          this.show = true;
        }, 0);
      });
    },
    sortId(a, b) {
      return a.order - b.order;
    },
    getFoods() {
      getFoods().then((res) => {
        this.caipinArr = res;
        
        this.caipinArr.forEach((item,index)=>{
          this.caipinArr[index].order = this.orderObj[item.caipin] || 100;
        })
        this.caipinArr.sort(this.sortId);
        this.getFabu();
      });
    },
    addFood() {
      let arr = this.caipinArr.filter((item) => {
        return this.foodName == item.caipin;
      });
      if (arr.length) {
        this.$message("不能重复添加菜品");
        return;
      }
      if (this.foodName=="") {
        this.$message("不能添加个寂寞");
        return;
      }
      addFood({ foodName: this.foodName }).then((res) => {
        this.getFoods();
        this.$message({
          message:"成功添加菜品",
          type:'success'
        });
      });
    },
    delFood() {
      if (this.foodName=="") {
        this.$message("不能删除个寂寞");
        return;
      }
      //询问框
      let arr = this.caipinArr.filter((item) => {
        return item.caipin == this.foodName;
      });
      if (arr.length) {
        this.$confirm("确定要删除吗？", "提示", {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "是的",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(() => {
          delFood({
              foodName: this.foodName,
            }).then((res) => {
              this.getFoods();
              let order = -1;
              this.caipinSelectArr.forEach((item, index) => {
                if (item == this.foodName) {
                  order = index;
                }
              });
              this.caipinSelectArr.splice(order, 1);
              this.$message({
                message:"成功删除此菜品",
                type:"success"
              })
            });
        })
        .catch(() => {});
      } else {
        this.$message("当前没有此菜品")
      }
    },
    delFabu() {
      if (this.fabuVisiable) {
        this.$confirm("今天已经有发布信息，是否删除今日所有发布？", "提示", {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定删除",
          cancelButtonText: "容我思量",
          type: "info",
        })
          .then(() => {
            this.delFabuOK();
          })
          .catch(() => {});
      } else {
        // this.fabuOK()
      }
    },
    fabuAgain(){
      this.fabu("again");
    },
    fabu() {
      this.$comment.createPoint({ tableName:"food", moduleName: "发布页", pageName: "/vesync/publish", eventName: "点击发布", localTime: new Date().Format("yyyy-MM-dd hh:mm:ss.S") })
      if (this.caipinSelectArr.length == 0) {
        this.$message("菜品不能为空");
        return;
      }
      if (this.startTime == "" || this.startTime == null) {
        this.$message("开始时间不能为空");
        return;
      }
      if (this.endTime == "" || this.endTime == null) {
        this.$message("结束时间不能为空");
        return;
      }
      let st = this.startTime.toString().includes("时间")
        ? this.startTime.FormatCopy("yyyy-MM-dd hh:mm:ss")
        : this.startTime;
      let et = this.endTime.toString().includes("时间")
        ? this.endTime.FormatCopy("yyyy-MM-dd hh:mm:ss")
        : this.endTime;
      let endTime = new Date(et.allReplace("-", "/"));
      let startTime = new Date(st.allReplace("-", "/"));
      if (startTime >= endTime) {
        this.$message("结束时间必须晚于开始时间");
        return;
      }
      if (this.fabuVisiable) {
        this.$confirm("今天已经有发布信息，是否再次发布？", "提示", {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定发布",
          cancelButtonText: "容我思量",
          type: "info",
        })
          .then(() => {
            this.fabuOK();
          })
          .catch(() => {});
      } else {
        this.fabuOK();
      }
    },
    delFabuOK() {
      if (this.faburen == "") {
        this.$message("发布人不能为空");
        return;
      }
      let person = this.yonghuArr.filter((item) => {
        return item.id == this.faburen;
      })[0].username;
      delFabu({
        nowDay: new Date().Format("yyyy-MM-dd"),
        faburen: person,
      }).then((res) => {
        this.$message({
          message: "删除发布成功",
          type: "success",
        });
        location.reload();
      });
    },
    fabuOK() {
      let nowTime = new Date();
      let year = nowTime.getFullYear();
      let month = nowTime.getMonth() + 1;
      let day = nowTime.getDate();
      let st = this.startTime.toString().includes("时间")
        ? this.startTime.FormatCopy("yyyy-MM-dd hh:mm:ss")
        : this.startTime;
      let et = this.endTime.toString().includes("时间")
        ? this.endTime.FormatCopy("yyyy-MM-dd hh:mm:ss")
        : this.endTime;
      st = new Date().Format("yyyy-MM-dd") + " " + st.split(" ")[1];
      et = new Date().Format("yyyy-MM-dd") + " " + et.split(" ")[1];
      let person = this.yonghuArr.filter((item) => {
        return item.id == this.faburen;
      })[0].username;
      fabu({
        nowDay: `${year}-${month}-${day}`,
        nowTime: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        faburen: person,
        startTime: st,
        endTime: et,
        caipinSelectArr: this.caipinSelectArr,
        remark: this.remark,
      }).then((res) => {
        this.getFoods();
        this.getYonghu();
        this.$message({
          message: "发布成功",
          type: "success",
        });
      });
    },
  },
};
</script>
<style lang="stylus" scoped>
.marginL10 {
  margin-left: 10px;
}

#about {
  width: 100%;
  min-height: 100%;
  position: absolute;
  background-image: url('../../assets/login_bg.svg');

  .moreDo {
    text-decoration: none;
    border-bottom: 1px solid #409EFF;
    padding: 0 2px 1px 2px;
    color: #409EFF;
    cursor: pointer;
    margin-left: 20px;
    font-size: 12px;
  }

  .goto {
    position: absolute;
    right: 10px;
    bottom: 10px;
    text-decoration: none;
    border-bottom: 1px solid #409EFF;
    padding: 0 5px 1px 5px;
    color: #409EFF;
    cursor: pointer;
  }

  .admin {
    width: 100%;
    /* height:100%; */
    display: flex;
    justify-content: center;
    align-items: center;
    /* background-color: #f0f2f5; */
  }

  .main {
    width: 640px;
    /* width:80%; */
    /* height:640px; */
    /* background-color: rgba(0, 0, 0, 0.6); */
  }

  .flex-x-y-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .row {
    // width: 100%;
    height: auto;
    display: flex;
    align-items: center;
    color: #262626;
    font-size: 15px;
    background-color: rgba(255, 255, 255, 0.6);
    border-radius: 10px;
    padding: 15px 15px;
    margin: 10px;
  }

  .left {
    flex-basis: 120px;
    text-align: right;
  }

  .middle {
    flex: 1;
    text-align: left;
  }

  .right {
    flex: 1;
    // text-align: left;
    margin-left: 10px;
  }

  .el-input__inner {
    width: 250px;
  }

  .row .info {
    display: flex;
    width: 100%;
  }

  .info .user {
    flex-basis: 120px;
    text-align: right;
  }

  .info .caipin {
    flex: 1;
    text-align: left;
  }

  .el-checkbox {
    margin: 10px 15px;
    width: 110px;
    /* color: white; */
  }

  a {
    color: #409EFF;
  }
}
</style>
<style lang="stylus">
#about {
  .el-checkbox__label {
    color: #262626;
  }

  .yonghu .el-select {
    width: 230px;
  }

  button {
    margin: 5px !important;
  }
}
</style>
